package com.example.securitytest.filter;

import com.example.securitytest.domain.LoginUser;
import com.example.securitytest.util.JwtUtil;
import com.example.securitytest.util.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        String token = httpServletRequest.getHeader("token");

        //  token为空
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            // 程序不再往下执行
            return;
        }

        String userid; // 把userid定义在外面，才能同时用于下面的46行和52行
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            // 抛出异常，程序不再执行
            throw new RuntimeException("token非法");
        }
        // 从redis中获取用户信息
        String redisKey = "login:" + userid;

      /*
        调用redisTemplate.opsForValue().set(key, value)方法，其中key是要设置的键值对应的键，value是要设置的键值对应的值。此处的value参数可以直接传入一个已经序列化为JSON格式的字符串；
        当从Redis中读取时，可以使用redisTemplate.opsForValue().get(key)方法获取到对应的值，返回结果会被自动反序列化为原始的Bean对象。
       */
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)) {
            // 抛出一个异常
            throw new RuntimeException("用户未登录");
        }

        // 把最终的LoginUser用户信息，通过setAuthentication方法，存入SecurityContextHolder
        // TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                // 第一个参数是LoginUser用户信息，第二个参数是凭证(null)，第三个参数是权限信息(null)
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

        // 将用户信息放在SecurityContextHolder中，这样经过那么
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 全部做完之后，就放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);


    }
}
